package a07_二叉树;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a05_二叉树的层序遍历复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/1/10
 */
public class a05_层序遍历01_二叉树的层序遍历复习2 {
    public static void main(String[] args) {
        Deque<Integer> deque = new LinkedList<>();
        deque.add(1);
        deque.add(2);

        System.out.println(deque.pollLast());//2

        TreeNode treeNode = new TreeNode(1);
        levelOrder(treeNode);


    }
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> resultList = new ArrayList<>();
        if (root == null) {
            return resultList;
        }
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);

        while (!deque.isEmpty()) {
            int size = deque.size();
            List<Integer> result = new ArrayList<>();
            while (size > 0) {
                TreeNode popNode = deque.pollFirst();
                result.add(popNode.val);

                if (popNode.left != null) {
                    deque.add(popNode.left);
                }

                if (popNode.right != null) {
                    deque.add(popNode.right);
                }
                size--;
            }
            resultList.add(result);
        }
        return resultList;
    }
}
